<template>
  <div class="categories-page">
    <div class="page-header">
      <h1>Categories Management</h1>
      <el-button type="primary" @click="openDialog()">
        <n-icon size="18" style="margin-right: 0.5rem;"><AddOutline /></n-icon>
        Add Category
      </el-button>
    </div>

    <!-- Categories Table -->
    <el-card>
      <el-table v-loading="loading" :data="categories" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="Name (CN)" />
        <el-table-column prop="name_en" label="Name (EN)" />
        <el-table-column prop="description" label="Description" />
        <el-table-column prop="display_order" label="Display Order" width="120" align="center" />
        <el-table-column prop="product_count" label="Products" width="100" align="center" />
        <el-table-column label="Actions" width="200" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="openDialog(row)">Edit</el-button>
            <el-popconfirm
              title="Are you sure to delete this category?"
              @confirm="deleteCategory(row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger">Delete</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Category Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogMode === 'create' ? 'Add Category' : 'Edit Category'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="Name (CN)" prop="name">
          <el-input v-model="formData.name" placeholder="分类名称" />
        </el-form-item>

        <el-form-item label="Name (EN)" prop="name_en">
          <el-input v-model="formData.name_en" placeholder="Category Name" />
        </el-form-item>

        <el-form-item label="Description" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="Category description"
          />
        </el-form-item>

        <el-form-item label="Display Order" prop="display_order">
          <el-input-number v-model="formData.display_order" :min="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          {{ dialogMode === 'create' ? 'Create' : 'Update' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { NIcon } from 'naive-ui'
import { AddOutline } from '@vicons/ionicons5'
import { ElMessage } from 'element-plus'
import { categoryAPI } from '@/api'

const loading = ref(false)
const categories = ref([])
const dialogVisible = ref(false)
const dialogMode = ref('create')
const submitting = ref(false)
const formRef = ref(null)

const formData = reactive({
  id: null,
  name: '',
  name_en: '',
  description: '',
  display_order: 0
})

const rules = {
  name: [{ required: true, message: 'Please enter name (CN)', trigger: 'blur' }],
  name_en: [{ required: true, message: 'Please enter name (EN)', trigger: 'blur' }]
}

const loadCategories = async () => {
  try {
    loading.value = true
    const response = await categoryAPI.getAll()
    if (response.success) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('Failed to load categories:', error)
  } finally {
    loading.value = false
  }
}

const openDialog = (category = null) => {
  if (category) {
    dialogMode.value = 'edit'
    Object.assign(formData, category)
  } else {
    dialogMode.value = 'create'
    resetForm()
  }
  dialogVisible.value = true
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    name_en: '',
    description: '',
    display_order: 0
  })
  formRef.value?.resetFields()
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    if (dialogMode.value === 'create') {
      await categoryAPI.create(formData)
      ElMessage.success('Category created successfully')
    } else {
      await categoryAPI.update(formData.id, formData)
      ElMessage.success('Category updated successfully')
    }
    
    dialogVisible.value = false
    loadCategories()
  } catch (error) {
    if (!error.message) {
      // Validation error
      return
    }
  } finally {
    submitting.value = false
  }
}

const deleteCategory = async (id) => {
  try {
    await categoryAPI.delete(id)
    ElMessage.success('Category deleted successfully')
    loadCategories()
  } catch (error) {
    console.error('Failed to delete category:', error)
  }
}

onMounted(() => {
  loadCategories()
})
</script>

<style lang="scss" scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  
  h1 {
    margin: 0;
    color: var(--text-primary);
  }
}
</style>

